import React,{useState,useEffect,useMemo,useCallback,useRef,createRef} from 'react'

const myset1 = new Set()
const myset2 = new Set()

function UseRef(props){
    // console.log('start')
    const [qty,setQty] = useState(1)
    const [page,setPage] = useState(1)

    // 创建ref对象
    // createRef()每次都会创建一个ref对象
    const ref1 = createRef() // 默认值为null

    // useRef()在初始化时创建ref对象并缓存,更新时得到缓存值
    const ref2 = useRef(10); // 可以设置默认值

    myset1.add(ref1)
    myset2.add(ref2)

    // console.log('ref1',myset1)
    console.log('ref2',myset2)

    // 设置定时器
    const [time,setTime] = useState(0)

    // useRef只创建一个ref对象,但ref.current可以随意改变
    const ref = useRef()
    ref.current = useCallback(function(){
        setTime(time+1)
    },[time])
    useEffect(()=>{
        // 为了保证只有一个定时器,useEffect必须指定空依赖
        setInterval(()=>{
            console.log('interval')
            ref.current()
        },1000)
    },[])
    
    const changeQty = useCallback(function(){
        setQty(qty+1)
    },[qty])
    const changePage = useCallback(()=>{
        setPage(page+1)
    },[page])

    // console.log('end')
    return (
        <div>
            <h4>useRef</h4>
            <button onClick={changeQty}>qty: {qty}</button>
            <button onClick={changePage}>page: {page}</button>
            <div>{time}</div>
        </div>
    )
}

export default UseRef;